<?php
class LoginAction extends BaseAction {

	public function Index() {
		$this->display();

	}

	//用户验证
	public function checkLogin() {

		$username = I('post.username');
		$password = I('post.password');
		$checkcode = I('post.checkcode');

		if ($username=='' || empty($username)) {
			$state = '请输入用户名';
			echo $this->echo_json_str($state,$message,$url);die;

		}
		elseif ($password=='' || empty($password)) {
			$state = '请输入密码';
			echo $this->echo_json_str($state,$message,$url);die;
		}
		elseif ($checkcode=='' || empty($checkcode)) {
			$state = '请输入验证码';
			echo $this->echo_json_str($state,$message,$url);die;
		}

		if ($_SESSION['verify'] != md5($checkcode)) {
			$state = '验证码不正确';
			echo $this->echo_json_str($state,$message,$url);die;
		}

        //生成认证条件
        $map = array();
        // 支持使用绑定帐号登录
        $map['username'] = $username;
        import('ORG.Util.RBAC');
        $authInfo = RBAC::authenticate($map);
        //使用用户名、密码和状态的方式进行认证
        if (!$authInfo) {
            $state = '帐号不存在或已禁用';
            echo $this->echo_json_str($state,$message,$url);die;
        } else {
            if ($authInfo['password'] != md5($_POST['password'])) {
                $state = '密码错误';
            	echo $this->echo_json_str($state,$message,$url);die;
            }
            $_SESSION[C('USER_AUTH_KEY')] = $authInfo['id'];
            if ($authInfo['username'] == 'admin') {
                $_SESSION['administrator'] = true;
            }

            $admin = M('Admin');
			$list = $admin->where("username='$username'")->find();
            setcookie('adminName',$list['username']);
			setcookie('adminGroup',$list['group']);
			setcookie('adminID',$list['id']);
			setcookie('adminFlag','alex1937818');

            //保存登录信息
			$log = M('AdminLog');
			$date['uid'] = $list['id'];
			$date['loginTime'] = time();
			$date['loginIP'] = get_client_ip();
			$list = $log->add($date);

			$_SESSION['adminName'] = $authInfo['username'];
			$_SESSION['adminFlag'] = 'alex1937818';

            // 缓存访问权限
            RBAC::saveAccessList();
            $state = 'SUCCESS';
            $message = '登录成功';
			$url = U('Index/index');
			echo $this->echo_json_str($state,$message,$url);die;
        }		

	}

	function exitSystem(){

		if (isset($_SESSION[C('USER_AUTH_KEY')])) {
            unset($_SESSION[C('USER_AUTH_KEY')]);
            unset($_SESSION['menu' . $_SESSION[C('USER_AUTH_KEY')]]);
            unset($_SESSION);
            session_destroy();
            setcookie('adminName','',time()-3600);
			setcookie('adminGroup','',time()-3600);
			setcookie('adminID','',time()-3600);
			setcookie('adminFlag','',time()-3600);
			$this->success('成功退出',U('Login/Index'));
        } else {
            $this->error('退出失败...');
        }			
	}

	//验证码显示
	public function verify() {

		import("ORG.Util.Image");
		Image :: buildImageVerify();

	}
}
?>